package com.hairline.hairlinemarket.service.impl;

import com.github.pagehelper.PageInfo;
import com.hairline.hairlinemarket.bean.*;
import com.hairline.hairlinemarket.bean.vo.OrderVo;
import com.hairline.hairlinemarket.mapper.*;
import com.hairline.hairlinemarket.service.OrderService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Author:杨小凯
 * Date:2023-04-22 17:44
 * Description:<描述>
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private MarketOrderMapper marketOrderMapper;
    @Autowired
    private MarketCartMapper marketCartMapper;
    @Autowired
    private MarketCouponMapper marketCouponMapper;
    @Autowired
    private MarketCouponUserMapper marketCouponUserMapper;
    @Autowired
    private MarketAddressMapper marketAddressMapper;
    @Autowired
    private MarketOrderGoodsMapper marketOrderGoodsMapper;

    @Override
    public Integer addOrder(OrderVo orderVo) {

        Subject subject = SecurityUtils.getSubject();
        MarketUser principal = (MarketUser) subject.getPrincipal();
        // 拿到了个人id信息
        Integer userId = principal.getId();
        // 查询当前用户选择的商品的总金额
        double goodsTotalPrice = marketCartMapper.selectCheckedGoodsAmount(userId).doubleValue();

        // 优惠券值
        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(orderVo.getCouponId());
        double couponPrice;
        if (marketCoupon!=null){
            couponPrice = marketCoupon.getDiscount().doubleValue();
        }else {
            couponPrice = 0;
        }
        // TODO 运费需要判断地址
        double freightPrice=0;
        // TODO 组团
        double grouponPrice=0;


        // TODO 积分减免
        double integralPrice = 0;

        // 订单总金额：实付订单货物金额+运费-优惠卷
        double orderPrice=goodsTotalPrice + freightPrice - couponPrice;
        // 实付订单货物金额
        double actualPrice=orderPrice - integralPrice;
        // 可用优惠券数量
        // 查询用户拥有的优惠券
        MarketCouponUserExample couponUserExample = new MarketCouponUserExample();
        couponUserExample.createCriteria().andUserIdEqualTo(userId);
        List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(couponUserExample);
        Integer availableCouponLength=marketCouponUsers.size();

        // 查询地址
        MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(orderVo.getAddressId());
        String addressDetail = marketAddress.getAddressDetail();
        String province = marketAddress.getProvince();
        String city = marketAddress.getCity();
        String county = marketAddress.getCounty();
        String address = province+city+county+addressDetail;
        String mobile = marketAddress.getTel();
        String consignee = marketAddress.getName();


        // 添加进入order表
        MarketOrder record = new MarketOrder();
        record.setUserId(userId);
        // TODO 订单编号 时间戳
        long orderSn = System.currentTimeMillis();
        record.setOrderSn(String.valueOf(orderSn));
        record.setOrderStatus((short) 201);
        record.setAftersaleStatus((short) 0);
        record.setConsignee(consignee);
        record.setMobile(mobile);
        record.setAddress(address);
        record.setMessage(orderVo.getMessage());
        record.setGoodsPrice(BigDecimal.valueOf(goodsTotalPrice));
        record.setFreightPrice(BigDecimal.valueOf(freightPrice));
        record.setCouponPrice(BigDecimal.valueOf(couponPrice));
        record.setIntegralPrice(BigDecimal.valueOf(integralPrice));
        record.setGrouponPrice(BigDecimal.valueOf(grouponPrice));
        record.setOrderPrice(BigDecimal.valueOf(orderPrice));
        record.setActualPrice(BigDecimal.valueOf(actualPrice));
        // 发货时间
        record.setShipTime(new Date());
        // 发货编号
        record.setShipSn(String.valueOf(orderSn));

        int orderAdd = marketOrderMapper.insertSelective(record);

        // 添加到order_goods
        MarketOrderGoods marketOrderGoods = new MarketOrderGoods();
        // 订单id
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        marketOrderExample.createCriteria().andOrderSnEqualTo(String.valueOf(orderSn));
        List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(marketOrderExample);
        Integer orderId = marketOrders.get(0).getId();
        marketOrderGoods.setOrderId(orderId);

        // 查询购物车
        // 选择的商品列表
        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andUserIdEqualTo(userId).andCheckedEqualTo(true).andDeletedEqualTo(false);
        List<MarketCart> checkedGoodsList = marketCartMapper.selectByExample(marketCartExample);
        for (MarketCart marketCart : checkedGoodsList) {
            Short number = marketCart.getNumber();
            Integer goodsId = marketCart.getGoodsId();
            String goodsName = marketCart.getGoodsName();
            String goodsSn = marketCart.getGoodsSn();
            BigDecimal price = marketCart.getPrice();
            Integer productId = marketCart.getProductId();
            String picUrl = marketCart.getPicUrl();
            String specifications = marketCart.getSpecifications();
            marketOrderGoods.setGoodsId(goodsId);
            marketOrderGoods.setGoodsName(goodsName);
            marketOrderGoods.setGoodsSn(goodsSn);
            marketOrderGoods.setProductId(productId);
            marketOrderGoods.setNumber(number);
            marketOrderGoods.setPrice(BigDecimal.valueOf((price.doubleValue()*number)));
            marketOrderGoods.setSpecifications(specifications);
            marketOrderGoods.setPicUrl(picUrl);
            int orderGoodsAdd = marketOrderGoodsMapper.insert(marketOrderGoods);

            // 根据productId删除购物车中的数据（逻辑删除）
            MarketCart cart = new MarketCart();
            cart.setDeleted(true);
            MarketCartExample example = new MarketCartExample();
            example.createCriteria().andProductIdEqualTo(productId);
            marketCartMapper.updateByExampleSelective(cart, example);
        }

        return orderId;
    }

    @Override
    public PageInfo selectByType(Map map,Integer userId) {

        Integer showType = (Integer) map.get("showType");

        PageInfo<Object> info = new PageInfo<>();
        switch (showType){
            case 0:
                // showType=0:全部

                break;
            case 1:
                // showType=1:待付款
                break;
            case 2:
                // showType=2:待发货
                break;
            case 3:
                // showType=3:待收货
                break;
            case 4:
                // showType=4:待评价
                break;
            default:
                return null;
        }
        return null;
    }
}
